import { Injectable } from '@angular/core';
import {SelfHttp} from "../http/service";
import {siteApi} from "../../api/site";

@Injectable({
  providedIn: 'root'
})
export class SiteService {
  siteInfo: any = localStorage.getItem('siteInfo') ? JSON.parse(localStorage.getItem('siteInfo') as string) : {};
  constructor(private selfHttp: SelfHttp) {
    this.selfHttp = selfHttp;
  }
  getSiteInfo(cb?: (data: any) => void) {
    this.selfHttp.post(siteApi.siteInfo, {}, (res: any) => {
      this.siteInfo = res;
      localStorage.setItem('siteInfo', JSON.stringify(res));
      cb && cb(this.siteInfo);
    })
  }
  async getSiteInfoAsync() {
    if(this.siteInfo.id){
      return this.siteInfo;
    }
    return new Promise((resolve, reject) => {
      this.getSiteInfo((res: any) => {
        localStorage.setItem('siteInfo', JSON.stringify(res));
        resolve(res);
      })
    })
  }
  getSiteListAsync(){
    return new Promise((resolve, reject) => {
      this.selfHttp.get(siteApi.siteList, {}, (res: any) => {
        resolve(res);
      })
    })
  }
  getSiteList(cb?: (data: any) => void) {
    this.selfHttp.get(siteApi.siteList, {}, (res: any) => {
      cb && cb(res);
    })
  }
  changeSite(siteId: string | number, cb?: (data: any) => void) {
    this.selfHttp.post(siteApi.changeSite, {site_id: siteId}, async (res: any) => {
      localStorage.removeItem('siteInfo');
      await this.getSiteInfoAsync();
      cb && cb(res);
    })
  }
}
